<?php
/**
 * Created by PhpStorm.
 * User: Bobo
 * Date: 2017/3/29
 * Time: 19:32
 */
ini_set('display_errors',1);            //错误信息
ini_set('display_startup_errors',1);    //php启动错误信息
error_reporting(-1);                    //打印出所有的 错误信息
//var_dump($_POST);
//echo json_encode($_POST);
//exit();
require_once "WxPay.NativePay.php";
require_once "lib/Base.php";

$channel_id = session('channel_id');
$openId = session('openid');
$player_id = session('user_id');
if (empty($openId)) {exit('error');}

$body = I('paytitle');
$total_fee = I('pay'); // 支付金额，单位为分
$game_id = I('_gameID');
$gparams = $_POST['gparams'];
if (empty($body) || !is_numeric($total_fee) || !is_numeric($game_id)) {exit('error');}
try{
    $tmp = json_decode($gparams, true);
    if (!is_array($tmp)) {exit('error');}
}catch (Exception $exception) {
    exit('error');
}


require_once 'lib/DB.php';
$db = new DB();
$channel = $db->getOne('appc_player', 'id='.$player_id, 'channel_id');
$channel_id = $channel['channel_id'];


$attach = ''; // 这里不设置，因为参数有可能很长，所以通过另外一种途径保存起来之后传值。
$time = microtime();
$trade_no = $channel_id.date("YmdHis").substr($time,2,6);// 商户订单号，生成规则其实随意，唯一就行，

$time_start = date("YmdHis"); // 订单时间
$time_expire = date("YmdHis", time() + 7200); // 订单过期时间，这里为2小时；
$notify_url = 'http://www.h5youx.com/game/test/notify.php'; // 支付成功回调地址
$trade_type = 'NATIVE'; // 支付方式，NATIVE 支付 二维码，
$product_id = 'pro_'.$total_fee;

$notify = new NativePay();

$input = new WxPayUnifiedOrder();
$input->SetBody($body);
$input->SetAttach($attach);
$input->SetOut_trade_no($trade_no);
$input->SetTotal_fee($total_fee);
$input->SetTime_start($time_start);
$input->SetTime_expire($time_expire);
//$input->SetGoods_tag("test");
$input->SetNotify_url($notify_url);
$input->SetTrade_type($trade_type);
$input->SetProduct_id($product_id);

try{
    $result = $notify->GetPayUrl($input);
    require_once 'lib/DB.php';
    



    $gmap = array('id'=>$game_id);
    $game_separate = $db->getOne('appc_game',$gmap,'separate');
    $game_separate = empty($game_separate)? '0' : $game_separate['separate'];

    $cmap = array('id'=>$channel_id);
    $channel_separate = $db->getOne('appc_channel',$cmap,'separate');
    $channel_separate = empty($channel_separate)? '0' : $channel_separate['separate'];

    $tmap = array('status'=>'1');
    $toll = $db->getOne('appc_toll',$tmap,'toll');
    $toll = empty($toll)? '0' : $toll['toll'];

    $map = array('channel_id'=>$channel_id, 'type'=>3, 'open'=>1);  // 这里直接写死为3
    $kou = $db->getOne('appc_channel_kou', $map);
    if(empty($kou)){
        $pay_show = $total_fee;
    }else{
        $day = date('Y-m-d 00:00:00');
        $map = array('channel_id'=>$channel_id, 'type'=>3, 'day'=>$day);
        $one = $db->getOne('appc_channel_data', $map);
        if (empty($one)) { // 插入
            $pay_show = getKouStep(0,0,$kou['max_v'],$kou['bi'],$total_fee);
        } else { // 更新
            $pay_show = getKouStep($one['value'], $one['show_value'], $kou['max_v'],$kou['bi'],$total_fee);
        }
    }


    $data = array(
        'trade_no'=>$trade_no,
        'player_id'=>$player_id,
        'pay'=>$total_fee,
        'game_id'=>$game_id,
        'callback_parms' =>$gparams,
        'game_separate'=>$game_separate,
        'channel_separate'=>$channel_separate,
        'toll'=>$toll,
        'pay_show'=>$pay_show
    );
    $rst = $db->insert('appc_trade',$data);
    $db->close();
    $a = print_r($rst,true);
    if ($rst) {
        $arr = array (
            'status'=>1,
            'data' => $result["code_url"],
            'rst' =>$a
        );
        echo json_encode($arr);
        exit();
    } else {
        exit('error');
    }
} catch (Exception $exception) {
    exit($exception->getMessage());
}


/**
 * @param $true 真实量
 * @param $show 显示量
 * @param $max_v 扣量临界值
 * @param $bi 扣量比例
 * @param $step 自增值
 */
function getKouStep ($true, $show, $max_v,$bi, $step=1){
    if (empty($bi)) return $step; // 如果比为0，则代表不扣量
    if (($true+$step) <= $max_v) {return $step;}
    $bi = $bi/1000;
    $idend = $true ? $true : 1 ;
    $true_bi = ($true - $show ) / $idend;
    if ($true_bi<$bi) { // 直接扣，没的说
        return  $step-floor($step * $bi);
    }
    return $step;
}



